<template>
  <div ref="page">
    <div class="item">
      <div class="title">
        <span>试用期考核权重</span>
        <div class="title-right">
          <a-button type="text" @click="minScoreVisible = true"
            >设置最低分</a-button
          >
        </div>
      </div>
      <a-alert v-if="weightTotal && weightTotal !== 100" type="error"
        >方案权重的和必须等于100.</a-alert
      >
      <a-table :columns="columns" :data="formData" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #minimumScore>
          {{ probationExamineData.minimumScore }}
        </template>
        <template #cycle="{ rowIndex }">
          <span v-if="formData[rowIndex].cycleStart">
            {{ formData[rowIndex].cycleStart }} 至
            {{ formData[rowIndex].cycleEnd }}
          </span>
          <span v-else>--</span>
        </template>
        <template #weight="{ rowIndex }">
          <a-input-number
            v-if="formData[rowIndex].isInput"
            v-focus
            v-model="formData[rowIndex].weight"
            style="width: 80px"
            @blur="formData[rowIndex].isInput = !formData[rowIndex].isInput"
            hide-button
          >
            <template #suffix> % </template>
          </a-input-number>
          <span v-else>
            <template v-if="formData[rowIndex].weight">
              {{ formData[rowIndex].weight }}%
            </template>
            <template v-else> -- </template>

            <icon-edit
              style="color: #88b0fd; cursor: pointer"
              @click="formData[rowIndex].isInput = !formData[rowIndex].isInput"
            />
          </span>
        </template>

        <!-- <template #optional="{ record, rowIndex }">
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="edit(record, rowIndex)"
            />
          </a-tooltip>
          <a-tooltip content="删除" position="left">
            <a-popconfirm content="是否确认删除该条数据?" @ok="del(rowIndex)">
              <icon-font
                type="icon-delete"
                :size="26"
                :style="{
                  cursor: 'pointer',
                  marginRight: '10px'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template> -->
      </a-table>
    </div>
    <!-- <div class="item">
      <div class="title">试用期考核等级</div>
      <div>
        <a-alert
          v-if="tableData[tableData.length - 1]?.startScore < 0"
          type="error"
          >分数范围必须大于等于0.</a-alert
        >
        <a-table :columns="levelColumns" :data="tableData" :pagination="false">
          <template #name="{ rowIndex }">
            <a-form-item field="name">
              <a-input v-model="tableData[rowIndex].name" />
            </a-form-item>
          </template>
          <template #range="{ rowIndex }">
            <a-space>
              <a-input-number
                hide-button
                class="level-input"
                v-model="tableData[rowIndex].startScore"
                :min="0"
                :max="
                  rowIndex === 0
                    ? tableData[rowIndex].endScore
                    : tableData[rowIndex].endScore - 1
                "
                @change="scoreChange"
              >
                <template #suffix> 分 </template>
              </a-input-number>
              <div class="level-lable">
                ≤ 分数
                <span v-if="rowIndex === 0">≤</span>
                <span v-else v-text="`<`"></span>
              </div>
              <a-input-number
                hide-button
                class="level-input"
                :disabled="rowIndex !== 0"
                v-model="tableData[rowIndex].endScore"
                :min="1"
              >
                <template #suffix> 分 </template>
              </a-input-number>
            </a-space>
          </template>
          <template #optional="{ record, rowIndex }">
            <a-tooltip content="删除" position="left">
             <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record, rowIndex)"
              >
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer',
                    marginRight: '10px'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table>
        <a-button type="text" @click="addLevel">
          <template #icon>
            <icon-plus />
          </template>
          新增等级
        </a-button>
      </div>
    </div> -->
    <div class="item">
      <div class="title">
        考核规则：考核方案设置绩效等级与评分的对应规则，试用期转正，系统将默认启用这些规则。
      </div>
      <a-space>
        <span>通过</span>
        <span>分数≥</span>
        <a-input-number
          v-model="probationExamineData.passScore"
          hide-button
          class="level-input"
          style="width: 100px"
          :min="0"
        >
          <template #suffix> 分 </template>
        </a-input-number>
      </a-space>
    </div>
  </div>
  <MinScoreDrawer
    v-model:visible="minScoreVisible"
    v-model:min-score="probationExamineData.minimumScore"
  />
</template>

<script setup lang="ts">
import type {
  ProbationExamine,
  ProbationAppraise,
  PersonnelAssessmentOptionLevel,
  PersonnelUserExaminationRules
} from '@/apis/human/base/variationManager/probation/type';
import { delExamineGrade } from '@/apis/human/base/variationManager/probation/index';
import { useVModel } from '@vueuse/core';
import AddInterviewModal from './AddInterviewModal.vue';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import MinScoreDrawer from './MinScoreDrawer.vue';

const props = withDefaults(
  defineProps<{
    data: (ProbationAppraise & { isInput?: boolean })[];
    userInfo: any;
    levelData: PersonnelAssessmentOptionLevel[];
    examinationRules: PersonnelUserExaminationRules;
    examineData: ProbationAppraise;
  }>(),
  {}
);
const emit = defineEmits([
  'update:data',
  'update:levelData',
  'update:examineData',
  'goBottom'
]);
const formData = useVModel(props, 'data', emit) || [];
const tableData = useVModel(props, 'levelData', emit);
const rules = useVModel(props, 'examinationRules', emit);
const probationExamineData = useVModel(props, 'examineData', emit);
const columns = ref<any>([
  {
    title: '序号',
    dataIndex: '',
    slotName: 'index'
  },
  {
    title: '考核方案名称',
    dataIndex: 'name'
  },
  {
    title: '方案权重',
    dataIndex: 'weight',
    slotName: 'weight',
    width: 100
  },
  {
    title: '最低分数',
    dataIndex: 'minimumScore',
    slotName: 'minimumScore',
    width: 100
  },
  {
    title: '考核周期',
    dataIndex: 'cycle',
    slotName: 'cycle'
  },
  {
    title: '预警提醒时间',
    dataIndex: 'earlyWarningTime',
    slotName: 'earlyWarningTime'
  },
  {
    title: '启动时间',
    dataIndex: 'startTime',
    slotName: 'startTime'
  }
  // {
  //   title: '操作',
  //   dataIndex: 'optional',
  //   slotName: 'optional',
  //   width: 200
  // }
]);
const levelColumns = ref<any>([
  {
    title: '等级名称',
    dataIndex: 'name',
    slotName: 'name',
    width: 100
  },
  {
    title: '分数范围',
    dataIndex: 'range',
    slotName: 'range',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'optional',
    slotName: 'optional',
    width: 80
  }
]);
const weightTotal = computed(() => {
  return formData.value.reduce((accumulator, currentValue) => {
    return accumulator + currentValue?.weight;
  }, 0);
});
const addLevel = async () => {
  if (!tableData.value?.length) {
    tableData.value.push({ userId: props.userInfo.id, name: '' });
    return;
  }
  const preScore = tableData.value[tableData.value.length - 1]?.startScore;
  // if (!preScore) {
  //   Message.error('请先修改最后等级分数大于0');
  //   return;
  // }
  tableData.value.push({
    userId: props.userInfo.id,
    name: '',
    endScore: preScore
  });
};
const scoreChange = () => {
  tableData.value.forEach((item, index) => {
    if (!index) return;
    item.endScore = tableData.value[index - 1]?.startScore;
  });
};
// const formRules = {
//   name: [
//     {
//       required: true,
//       message: '请输入'
//     }
//   ],
//   cycleStart: [
//     {
//       required: true,
//       message: '请输入'
//     }
//   ]
// };
const del = async (data: PersonnelAssessmentOptionLevel, index: number) => {
  if (data.id) {
    await delExamineGrade({ ids: [data.id] });
  }
  tableData.value.splice(index, 1);
};
const validate = () => {
  let check = void 0;
  if (weightTotal.value && weightTotal.value !== 100) {
    Message.error('方案权重的和必须等于100.');
    return {};
  }

  if (tableData.value[tableData.value.length - 1]?.startScore < 0) {
    Message.error('分数范围必须大于等于0.');
    return {};
  }
  return check;
};
const minScoreVisible = ref(false);
defineExpose({ validate });
</script>
<style lang="less" scoped>
.item {
  margin-bottom: 36px;
  .title {
    font-weight: 600;
    font-size: 14px;
    background: #f5f7fb;
    padding: 5px 0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    &::before {
      content: '';
      margin: 0 5px;
      display: inline-block;
      width: 3px;
      height: 12px;
      border-left: #409efe solid 1px;
      background: #409efe;
    }
    .title-right {
      flex: 1;
      text-align: right;
    }
  }
}
.arco-form-item {
  margin: 0;
}
</style>
